package cn.uncode.springcloud.admin.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.uncode.schedule.ConsoleManager;
import cn.uncode.schedule.core.TaskDefine;
import cn.uncode.springcloud.starter.web.result.R;


@Controller
@RequestMapping("/task")
public class TaskController {
	
	@RequestMapping(value = "/instances" , method = RequestMethod.GET)
    @ResponseBody
    public R<List<Map<String, Object>>> instances(){
    	List<Map<String, Object>> rtMap = new ArrayList<>();
    	List<String> servers = null;
		try {
			servers = ConsoleManager.getScheduleManager().getScheduleDataManager().loadScheduleServerNames();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
    	if(servers != null){
    		for(int i=0; i< servers.size();i++){
    			String ser = servers.get(i);
    			Map<String, Object> obj = new HashMap<>();
				obj.put("id", i+1);
				obj.put("name", ser);
				boolean rt = false;
				try {
					rt = ConsoleManager.getScheduleManager().getScheduleDataManager().isLeader(ser, servers);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if(rt){
					obj.put("isMaster", "是");
				}else{
					obj.put("isMaster", "否");
				}
				rtMap.add(obj);
    		}
    	}
    	return R.success(rtMap);
    }

    @RequestMapping(value = "/list" , method = RequestMethod.GET)
    @ResponseBody
    public R<List<TaskDefine>> list(@RequestParam int page, @RequestParam int limit){
    	List<TaskDefine> tasks = ConsoleManager.queryScheduleTask();
        return R.success(tasks);
    }
    
    @RequestMapping(value = "/home" , method = RequestMethod.GET)
    @ResponseBody
    public R<Map<String, Object>> home(){
    	Map<String, Object> rtMap = new HashMap<>();
    	int run = 0, stop = 0, success = 0, error = 0;
    	List<TaskDefine> daily = new ArrayList<>();
    	Map<String, TaskDefine> days = new HashMap<>();
    	List<TaskDefine> tasks = ConsoleManager.queryScheduleTask();
    	for(TaskDefine task:tasks) {
    		if(task.isStop()) {
    			stop++;
    		}
    		if(task.isRunning()) {
    			run++;
    			success += task.getRunTimes();
    		}
    		if(task.isError()) {
    			error++;
    		}
    		if(task.isSingleTask()) {
    			if(StringUtils.isNotBlank(task.getCronExpression())) {
    				String[] strs = task.getCronExpression().split("\\s+");
    				if(strs != null) {
    					if("*".equals(strs[3])) {
    						daily.add(task);
    					}else {
    						days.put(strs[3], task);
    					}
    				}
    			}
    		}
    	}
    	rtMap.put("running", run);
    	rtMap.put("stop", stop);
    	rtMap.put("success", success);
    	rtMap.put("error", error);
    	rtMap.put("daily", daily);
    	rtMap.put("days", days);
        return R.success(rtMap);
    }

    @RequestMapping(value = "/delete" , method = RequestMethod.GET)
    @ResponseBody
    public  R<Boolean> delete(@RequestParam String targetBean, @RequestParam String targetMethod, @RequestParam String extKeySuffix){
    	if(StringUtils.isNotBlank(targetBean) && StringUtils.isNotBlank(targetMethod)) {
    		TaskDefine taskDefine = new TaskDefine();
			taskDefine.setTargetBean(targetBean);
			taskDefine.setTargetMethod(targetMethod);
			if(StringUtils.isNotBlank(extKeySuffix)){
				taskDefine.setExtKeySuffix(extKeySuffix);
			}
			ConsoleManager.delScheduleTask(taskDefine);
			return R.success();
    	}
        return R.failure();
    }
    
    @RequestMapping(value = "/add" , method = RequestMethod.POST)
    @ResponseBody
    public  R<Boolean> add(@RequestBody TaskDefine task){
		if(task.getThreadNum() > 1){
			task.setType(TaskDefine.TYPE_UNCODE_MULTI_MAIN_TASK);
		}else{
			task.setType(TaskDefine.TYPE_UNCODE_SINGLE_TASK);
		}

		if(StringUtils.isNotEmpty(task.getCronExpression()) || task.getPeriod() > 0 || null != task.getStartTime()){
			ConsoleManager.addScheduleTask(task);
			return R.success();
		}
        return R.failure();
    }
    
    
    @RequestMapping(value = "/update" , method = RequestMethod.POST)
    @ResponseBody 
    public R<Boolean> edit(@RequestBody TaskDefine task){
    	ConsoleManager.updateScheduleTask(task);
        return R.success();
    }
    
    

    


}
